import { createRouter, createWebHistory, RouterOptions } from 'vue-router';
import { getToken } from './util/token';
import { Index, Login, Register, User, UserStore, UserStoreProduct, Search, Product, NotFound, ShoppingCart, PlaceOrder, OrderSuccess } from "./views/views";

const routes: RouterOptions["routes"] = [
  {
    path: '/',
    name: 'index',
    component: Index
  },
  {
    path: '/search',
    name: 'search',
    component: Search
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/register',
    name: 'register',
    component: Register
  },
  {
    path: '/user',
    name: 'user',
    component: User,
    meta: { requiresAuth: true }
  },
  {
    path: '/user/store/:storeId',
    name: 'userStore',
    component: UserStore,
    meta: { requiresAuth: true }
  },
  {
    path: '/user/store/:storeId/product/:productId',
    name: 'userStoreProduct',
    component: UserStoreProduct,
    meta: { requiresAuth: true }
  },
  {
    path: '/store/:storeId',
    name: 'store',
    component: Product
  },
  {
    path: '/store/:storeId/product/:productId',
    name: 'product',
    component: Product
  },
  {
    path: '/cart',
    name: 'cart',
    component: ShoppingCart,
    meta: { requiresAuth: true }
  },
  {
    path: '/placeOrder',
    name: 'placeOrder',
    component: PlaceOrder,
    meta: { requiresAuth: true }
  },
  {
    path: '/orderSuccess',
    name: 'orderSuccess',
    component: OrderSuccess,
    meta: { requiresAuth: true }
  },

  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound,
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

router.beforeEach((to, _) => {
  const token = getToken();
  if (to.meta.requiresAuth && !token) {
    return {
      name: 'login',
      query: { redirect: to.fullPath }
    }
  }
});

export default router;